<?php
namespace Service;

class System extends Base
{

    public function getTables()
    {
        $tables = [];
        $list = getConfig('mysql');
        $corePdo = $this->get(CORE_PDO);
        foreach($list as $k => $v){
            $database = $v['dbname'];
            $pdo = $corePdo->get($k);
            $sm = $pdo->prepare("select table_name from information_schema.tables where table_schema='{$database}'");
            $sm->execute();
            $datas = $sm->fetchAll();
            foreach($datas as $data){
                $tables[] = "{$database}.{$data->table_name}";
            }
        }
        return array_unique($tables);
    }

    public function getDatabases()
    {
        $databases = [];
        $list = getConfig('mysql');
        foreach($list as $v){
            $databases[] = $v['dbname'];
        }
        return array_unique($databases);
    }

    public function getDatabaseConfigKeys()
    {
        $keys = [];
        $list = getConfig('mysql');
        foreach($list as $k => $v){
            $keys[] = $k;
        }
        return array_unique($keys);
    }

    public function getCreateTableSql($table, $note)
    {
        return "create table `{$table}` (`id` bigint(20) unsigned not null auto_increment,primary key (`id`)) engine=innodb auto_increment=1 default character set=utf8 default collate=utf8_general_ci comment='{$note}'";
    }

    public function getAddColumnSql($table, $field, $ext)
    {
        $type = $ext->dry_field_type_data->dry_type;
        return "alter table `{$table}` add column `{$field}` {$type}";
    }

    public function getDropColumnSql($table, $field)
    {
        return "alter table `{$table}` drop column `{$field}`";
    }

    public function getModifyColumnSql($table, $field, $ext)
    {
        $type = $ext->dry_field_type_data->dry_type;
        return "alter table `{$table}` modify `{$field}` {$type}";
    }

    public function createTable($key, $table, $note)
    {
        $pdo = $this->get(CORE_PDO)->get($key);
        $sql = $this->getCreateTableSql($table, $note);
        $sm = $pdo->prepare($sql);
        $sm->execute();
    }

    public function adjustField($key, $sql)
    {
        $pdo = $this->get(CORE_PDO)->get($key);
        $sm = $pdo->prepare($sql);
        $sm->execute();
    }

    public function getTableFields($key, $table)
    {
        $config = getConfig('mysql', $key);
        $database = $config['dbname'];
        $pdo = $this->get(CORE_PDO)->get($key);
        $sql = "select * from information_schema.columns where table_schema='{$database}' and table_name='{$table}'";
        $sm = $pdo->prepare($sql);
        $sm->execute();
        return $sm->fetchAll();
    }

}